#!/usr/bin/env python3
#-*- coding:utf-8 -*-

def bytes2array(data:bytes, val_bytes=4):
    # 如果文件大小不是val_bytes的倍数，则填充0
    if len(data) % val_bytes:
        data += b'\x00' * (val_bytes - len(data) % val_bytes)

    c_array = []
    for i in range(0, len(data), val_bytes):
        val = int.from_bytes(data[i:i+val_bytes], 'little')
        c_array.append(val)

    return c_array

def main(args):
    val_bytes = args.nbytes
    if val_bytes == 1:
        pstr = lambda n : f"0x{n:02x}"
    elif val_bytes == 2:
        pstr = lambda n : f"0x{n:04x}"
    elif val_bytes == 4:
        pstr = lambda n : f"0x{n:08x}"
    else:
        raise ValueError(f"val_bytes must be 1, 2 or 4")

    with open(args.file, 'rb') as f:
        data = f.read()

    c_array = bytes2array(args.file, val_bytes)
    print('uint32_t data[] = {')
    for idx, num in enumerate(c_array):
        if idx % 4 == 0:
            print('\n    ', end='')
        print(f"{pstr(num)}, ", end='')
    print('\n};')


if __name__ == '__main__':
    import sys
    import argparse

    argp = argparse.ArgumentParser(description='Convert binary file to C array')
    argp.add_argument('-n', '--nbytes',
                      type=int, default=4, choices=(1, 2, 4),
                      help='bytes of each value')
    argp.add_argument('file', help='binary file path')

    args = argp.parse_args()

    main(args)

